package top.my.http;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.example.util.Runner;
import org.apache.log4j.Logger;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 网页
 */
public class WebServer extends AbstractVerticle {
    final Logger logger = Logger.getLogger(WebServer.class);
    private List<String> fileList;
    private String WEB_DIR = "D:\\Java\\vertx\\src\\main\\java\\io\\vertx\\example\\core\\http\\simpleform\\";

    // Convenience method so you can run it in your IDE
    public static void main(String[] args) {
        Runner.runExample(WebServer.class);
    }

    @Override
    public void start() throws Exception {
        fileList = getAllFile(new File(WEB_DIR));
        //logger.info("fileList: " + fileList);
        vertx.createHttpServer().requestHandler(new Handler<HttpServerRequest>() {
            @Override
            public void handle(HttpServerRequest req) {
                //System.out.println("reqhead=" + req.headers());
                logger.info("req.uri(): " + req.uri());
                logger.info("reqbody: " + req.params());
                String url = req.uri().substring(1);
                if (!url.contains(".html")) {
                    url += ".html";
                }
                logger.info("url: " + url);
                if (fileList != null && fileList.contains(url)) {
                    req.response().sendFile(WEB_DIR + url);
                } else {
                    req.response().putHeader("content-type", "text/html").end("<html><body><h1>404没找到页面</h1></body></html>");
                }
            }
        }).listen(80).onSuccess(ar -> {
            logger.info("Web服务启动成功");
        }).onFailure(fail->{
            logger.info("Web服务启动失败");
        });
    }

    /**
     * 获取指定文件夹下所有文件，不含文件夹里的文件
     *
     * @param dirFile 文件夹
     * @return
     */
    public List<String> getAllFile(File dirFile) {
        // 如果文件夹不存在或着不是文件夹，则返回 null
        if (Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile())
            return null;

        File[] childrenFiles = dirFile.listFiles();
        if (Objects.isNull(childrenFiles) || childrenFiles.length == 0)
            return null;

        List<String> files = new ArrayList<>();
        for (File childFile : childrenFiles) {
            // 如果是文件，直接添加到结果集合
            if (childFile.isFile()) {
                String path = childFile.getPath();
                String lastPath = path.substring(path.lastIndexOf("\\") + 1, path.length());
                files.add(lastPath);
            }
        }
        return files;
    }
}
